package models

import (
	"fmt"
	"ginim/utils"
	"gorm.io/gorm"
)

type Contact struct {
	gorm.Model
	OwnerId     uint // 谁的关系
	TargetId    uint //
	Type        int  // 对应的类型 好友1 群2 3
	Description string
}

func (t *Contact) TableName() string {
	return "contact"
}

func FindFriends(userId uint) []User {
	//1查询关系表、2查询用户表

	friends := make([]Contact, 0)
	ids := make([]uint64, 0)
	utils.DB.Where("owner_id = ? and type=1", userId).Find(&friends)

	for _, v := range friends {
		fmt.Println(v)
		ids = append(ids, uint64(v.TargetId))
	}

	users := make([]User, 0)
	if len(ids) == 0 {
		return users
	}
	utils.DB.Where("id in ?", ids).Find(&users)

	return users
}

func AddFriend(userId uint, name string) (int, string) {
	user := User{}
	if name != "" {
		user = FindUserByName(name)
		if user.Salt != "" {
			if userId == user.ID {
				return -1, "无法添加自己为好友"
			}

			// 是否已经添加过好友
			contactExist := Contact{}
			utils.DB.Where("owner_id = ? and target_id = ? and type = 1", userId, user.ID).Find(&contactExist)
			if contactExist.ID != 0 {
				return -1, "该用户已经是你的好友"
			}

			// 事务
			transaction := utils.DB.Begin()

			// 事务开始后，无论什么异常都会rollback
			defer func() {
				if r := recover(); r != nil {
					transaction.Rollback()
				}
			}()

			contactMe := Contact{}
			contactMe.OwnerId = userId
			contactMe.TargetId = user.ID
			contactMe.Type = 1
			if err := utils.DB.Create(&contactMe).Error; err != nil {
				// 回滚
				transaction.Rollback()
				return -1, "添加好友失败"
			}

			contactOther := Contact{}
			contactOther.OwnerId = user.ID
			contactOther.TargetId = userId
			contactOther.Type = 1
			if err := utils.DB.Create(&contactOther).Error; err != nil {
				// 回滚
				transaction.Rollback()
				return -1, "添加好友失败"
			}

			transaction.Commit()

			return 0, "添加好友成功"
		}
		return -1, "找不到该用户"
	}
	return -1, "用户名称不能为空"
}

func FindUserByCommunityId(cId uint) []uint {
	ids := make([]uint, 0)
	contacts := make([]Contact, 0)

	utils.DB.Where("target_id = ? and type = 2", cId).Find(&contacts)
	for _, v := range contacts {
		ids = append(ids, v.OwnerId)
	}

	return ids
}
